<template>
  <div class="app-container add-page">
    <div class="container-fluid">
      <div class="filter-container addUserList">
        <div v-if="list" class="at ul-input" style="padding-bottom:20px;justify-content: flex-start">
          <h3><span>{{ list.matchEvent.competition }} </span>  <!-- <span>{{ list.matchEvent.activitiesName }}</span> -->  <span>{{ list.matchEvent.startDate | dateFormat }}</span></h3>
          <h4 v-if="list.scene"><span>{{ list.scene.sportName }}</span> <span>{{ list.scene.eventProject }}</span> <span>{{ list.scene.eventName }}</span> <span>{{ list.scene.typeName }}</span></h4>
        </div>
        <el-form ref="formData" :model="formData" :rules="rules" class="event-from">
          <el-form-item prop="userId">
            <el-autocomplete
              v-model="athleteData.name"
              :fetch-suggestions="queryAthleteSearchAsync"
              :clearable="true"
              placeholder="Athlete name"
              style="width: 270px;margin-right: 10px"
              @select="athleteshandleSelect"
            />
          </el-form-item>
          <el-form-item prop="resultClass">
            <el-input v-model="formData.resultClass" placeholder="Class" />
            <!-- <el-select  v-model="formData.resultClass" placeholder="Class" style="width: 260px">
              <el-option v-for="item in CLASS_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
            </el-select> -->

          </el-form-item>
          <el-form-item prop="resultContent"><el-input v-model="formData.resultContent" placeholder="Result" style="width: 260px" /></el-form-item>
          <el-form-item prop="achievement"><el-input v-model="formData.achievement" placeholder="成績" style="width: 260px" /></el-form-item>
          <el-form-item prop="ranking"><el-input v-model="formData.ranking" placeholder="Ranking" style="width: 200px" /></el-form-item>
          <!--          <el-input v-model="formData.awards" placeholder="Awards"></el-input>-->
          <el-form-item prop="awards">
            <el-select v-model="formData.awards" placeholder="Awards" style="width: 200px">
              <el-option v-for="item in AWARD_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item prop="remark"><el-input v-model="formData.remark" placeholder="Remarks" style="width: 230px" /></el-form-item>
          <el-form-item prop="resultTeam"><el-input v-model="formData.resultTeam" placeholder="Team" style="width: 230px" /></el-form-item>
          <el-button type="button" class="el-button el-button--success" :loading="buttonDisable" @click="onSubmit('formData')"><span>Add</span></el-button>
        </el-form>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list.resultList"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        stripe
        @sort-change="sort_change"
      >

        <el-table-column sortable="custom" prop="lastName" label="Name">
          <template slot-scope="scope">
            <el-autocomplete
              v-if="scope.row.edit"
              v-model="scope.row._athleteName"
              :fetch-suggestions="queryAthleteSearchAsync"
              :clearable="true"
              :placeholder=" scope.row.lastName +' '+scope.row.firstName +' '+scope.row.tcName"
              style=""
              @select="(item)=>athleteshandleSelect(item,scope.row)"
            />
            <span v-else>{{ scope.row.lastName +' ' }} {{ scope.row.firstName +' ' }} {{ scope.row.tcName }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="resultClass" label="Class">
          <template slot-scope="scope">
            <!-- <el-select v-model="scope.row._resultClass" placeholder="Sport Select" style="min-width: 180px">
              <el-option v-for="item in CLASS_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
            </el-select> -->
             <el-input  v-if="scope.row.edit" v-model="scope.row._resultClass" placeholder="Class" />
            <span v-else>{{ scope.row.resultClass }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="resultContent" label="Result">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model="scope.row._resultContent" />
            <span v-else>
              {{ scope.row.resultContent }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="achievement" label="成績">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model="scope.row._achievement" />
            <span v-else>
              {{ scope.row.achievement }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="ranking" label="Ranking">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model="scope.row._ranking" />
            <span v-else>
              {{ scope.row.ranking }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="awards" label="Awards">
          <template slot-scope="scope">
            <el-select v-if="scope.row.edit" v-model="scope.row._awards" placeholder="Awards">
              <el-option v-for="item in AWARD_TYPE" :key="item.value" :label="item.typeName" :value="item.id" />
            </el-select>
            <span v-else> {{ scope.row.awardsName }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="remark" label="Remarks">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" v-model="scope.row._remark" />
            <span v-else>
              {{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" prop="resultTeam" label="Teams">
          <template slot-scope="scope">
              <el-input v-if="scope.row.edit" v-model="scope.row._resultTeam" />
            <span v-else>
              {{ scope.row.resultTeam }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column sortable='custom' prop='' label="Notices">
          <template slot-scope="scope">
            {{ scope.row.notices }}
          </template>
        </el-table-column> -->

        <el-table-column fixed="right" label="" width="100">
          <template slot-scope="scope">
            <EditDel :scope="scope" @confirmEdit="confirmEdit" @del="del" />
          </template>
        </el-table-column>
      </el-table>

      <Pagination

        layout="sizes, prev, pager, next"
        :page-size="listQuery.size"
        :current-page="listQuery.page"
        :total="listQuery.total"
        class="pagination-container"
        :page-sizes="[25, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />

      <div class="t-center">
      	<el-button type="success" @click='$router.push({path:"/event/addlist",query:{id:$route.query.eventId}})' >Back</el-button>
      </div>
    </div>
  </div>
</template>

<script>
    // import { getInterList } from '@/api/home'
    import { addEventAthlete, modifyEventAthlete, delEventAthlete, getEventAthlete, getEventScene } from '@/api/event'
    import { queryAthletesList, getBelongingTypes } from '@/api/setting'
    import { getTypeName } from '@/utils'

    export default {
        data() {
          var checkAge = (rule, value, callback) => {
                  if (!value) {
                    return callback(new Error('年龄不能为空'))
                  }
                  setTimeout(() => {
                    if (!Number.isInteger(value)) {
                      callback(new Error('请输入数字值'))
                    } else {
                      if (value < 18) {
                        callback(new Error('必须年满18岁'))
                      } else {
                        callback()
                      }
                    }
                  }, 1000)
                }
            return {
              listLoading: false,
              buttonDisable: false,
                list: {
                  matchEvent: {},
                  scene: {},
                    resultList: []
                },
                listQuery: {
                    keyword: '',
                    page: 1,

                    total: 1,
                    sorting: 0,
                    column: '',
                    size: 20
                },
                listLoad0ing: true,
                link: '/event/addEdit',
                AWARD_TYPE: [],
                CLASS_TYPE: [],
                restaurants: [],
                athleteData: {
                    name: '', id: '', list: []
                },
                formData: { sceneId: '', userId: '', achievement: '', resultContent: '', resultClass: '', remark: '', ranking: '', awards: '', resultTeam: '' },
                rules: {
                    userId: [
                       { required: true, message: 'Athlete doesno exist in the system' }
                    ],
                    achievement: [
                        { required: false, message: '成绩 cannot be empty', trigger: 'blur' }
                    ],
                    resultClass: [
                        { required: true, message: 'Class cannot be empty', trigger: 'blur' }
                    ],
                    resultContent: [
                        { required: false, message: 'Content cannot be empty', trigger: 'blur' }
                    ],
                    ranking: [
                        { required: false, message: 'Ranking cannot be empty', trigger: 'blur' }
                    ],
                    awards: [
                        { required: false, message: 'Please select', trigger: ['change', 'blur'] }
                    ],
                    remark: [
                        { required: false, message: 'Please input', trigger: 'blur' }
                    ],
                    resultTeam: [
                        { required: true, message: 'Team cannot be empty', trigger: 'blur' }
                    ]
                }
            }
        },
        watch:{
          ['list.resultList'](val){
           console.log("312",val)
          }
        },
        created() {
            const query = this.$route.query
            if (query.id) {
                this.formData.sceneId = query.id
            }
            this.fetchData()

            // this.restaurants = this.loadAll()
        },
        methods: {
            onSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                      this._buttonDisable(this,'buttonDisable')
                      const params = {}
                      const list = this.list
                      Object.assign(params, this.formData)
                      addEventAthlete(params).then(response => {
                        this._buttonDisable(this,'buttonDisable',false)
                          // eslint-disable-next-line no-unused-vars
                          const data = response.result
                          if (response.status === 0) {
                              // this.formData = { sceneId: this.formData.sceneId, userId: '', achievement: '', resultContent: '', resultClass: '', remark: '', ranking: '', awards: '', resultTeam: '' }
                              // this.athleteData.name = ''
                              // this.athleteData.id = ''
                              // response.result.awards = getTypeName(response.result.awards, this.AWARD_TYPE)
                              // list.resultList.push(response.result)
                              this.getEventAthlete()
                              this.$message({
                                  type: 'success',
                                  message: response.msg
                              })
                          }
                      })
                  }
                })
            },
            sort_change(column) {
                this.listQuery.page = 1
                if (column.prop && column.order) {
                    this.listQuery.sorting = column.order ? column.order === 'ascending' ? 0 : 1 : !this.listQuery.sorting ? 1 : 0
                    this.listQuery.column = column.prop
                    this.getEventAthlete()
                }
            },
            fetchData() {
                this.getEventAthlete()

                getBelongingTypes({ belonging: 'EVENT' }).then(response => {
                    const data = response.result
                    this.AWARD_TYPE = data.AWARD_TYPE
                    this.CLASS_TYPE = data.CLASS_TYPE
                   // this.AWARD_TYPE = data.AWARD_TYPE
                })
            },
            getEventAthlete(formData) {
                getEventAthlete({
                    sceneId: this.formData.sceneId,
                    keyword: this.listQuery.keyword,
                    page: this.listQuery.page,
                    sorting: this.listQuery.sorting,
                    column: this.listQuery.column,
                    size: this.listQuery.size
                }).then(response => {
                    this.list = response.result
                    this.listLoading = false
                })
            },
            queryAthleteSearchAsync(queryString, cb) {
                if (queryString === '') {
                    cb([])
                    return false
                }
                var restaurants = this.restaurants
                queryAthletesList({ name: queryString }).then(response => {
                    // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
                    var results = []; var data = response.result

                    for (var i in data) {
                       this.isvalidator = queryString.indexOf(data[i].lastName + data[i].firstName) > -1
                        results.push({
                            value: data[i].lastName + ' ' + data[i].firstName,
                            name: data[i].lastName + ' ' + data[i].firstName + ' ' + data[i].hkId,
                            sportClass:data[i].sportClass,
                            sport:data[i].sport,
                            id: data[i].userId
                        })
                    }
                    clearTimeout(this.timeout)
                    this.timeout = setTimeout(() => {
                        cb(results)
                    }, 200 * Math.random())
                })
            },
            createStateFilter(queryString) {
                return (state) => {
                    return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
                }
            },
            athleteshandleSelect(item,row) {
              if(!row){
                this.athleteData.name = item.name
                this.athleteData.id = item.id
                this.formData.userId =  item.id
                this.formData.resultClass= item.sportClass
              }else{

               // this.list.resultList.value(row,'_resultClass',item.sportClass)
               // this.list.resultList.$set(row,'userId', item.id)
       
               this.$set(row,'userId',item.id)
               this.$set(row,'_resultClass',item.sportClass)
               //this.$set(row,'resultClass',item.sportClass)
               // row.resultClass = item.sportClass

              }

            },
            confirmEdit(row) {
                if (row.loading) return false
                //this._buttonDisable(row.loading)
                const list = this.list.sceneList
                const { id, sceneId,
                userId:userId,
                  _achievement:achievement,
                 _resultContent:resultContent,
                  _resultClass:resultClass,
                   _remark:remark,
                   _ranking:ranking,
                   _awards:awards,
                    _resultTeam:resultTeam } = row
                    debugger
                // this._buttonDisable(row.loading)
                addEventAthlete({ id,
                   sceneId, userId, achievement, resultContent, resultClass, remark, ranking, awards, resultTeam
                    }).then(response => {
                     // this._buttonDisable(this.buttonDisable)
                     const statu = response.status === 0
                     // this._buttonDisable(row.loading, true)
                    if (statu) {
                        let resultLesson=response.result
                        for(var k in resultLesson ){
                          this.$set(row,k,resultLesson[k])
                        }
                    }
                    this.$message({
                        message: response.msg,
                        type: statu ? 'success' : 'warning'
                    })
                })
            },

            del(id) {
                this.$confirm('This action will permanently delete this item. Do you want to continue?', 'Tips', {
                    confirmButtonText: 'Yes',
                    cancelButtonText: 'No',
                    type: 'warning'
                }).then(() => {
                    delEventAthlete({ id: id }).then(response => {
                        if (response.status === 0) {
                            this.$message({
                                type: 'success',
                                message: response.msg
                            })
                            this.fetchData()
                        }
                    })
                }).catch(() => {

                })
            },
            // pageSize变化事件
            handleSizeChange(val) {
              this.listQuery.limit = val
              this.fetchData()
            },
            // pageNum变化事件
            handleCurrentChange(page) {
                // this.trainScheduleList(page, this.activeName)
            },
            sportMedicineFormatLink(row, column) {
                return row.row.id = 1
            }
        }
    }
</script>
<style scoped="scoped" lang="scss">
   .addUserList{
     .event-from{
       text-align: left;
     }
     .event-from .el-input{
       margin-right:5px;
     }
     .el-form-item__content >*{
          // max-width:10% !important;
          width:100% !important;
     }
     .event-from .el-form-item{
       margin-right:0px;
       margin-bottom:30px;
       width:10%;
       display: inline-block;
     }
     .event-from .el-input input{
       border-radius: 0;
     }
   }

  .addUserList .at span{color: #586982;margin-right: 20px;}
</style>
